package com.happy_hao.topbiz.config;

import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.StandardCharsets;

public class HutoolJsonRedisSerializer implements RedisSerializer<Object> {
    @Override
    public byte[] serialize(Object object) throws SerializationException {
        if (object == null) {
            return new byte[0];
        }
        return JSONUtil.toJsonStr(object).getBytes();
    }

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        String str = new String(bytes, StandardCharsets.UTF_8);
        // 尝试解析为 JSON 对象，如果失败则返回原始字符串
        try {
            return JSONUtil.parseObj(str);
        } catch (Exception e) {
            // 如果解析失败，返回原始字符串
            return str;
        }
    }
}
